import { AppDataSource } from '../src/config/database';
import { CreditPackage } from '../src/entities/CreditPackage';

/**
 * 初始化信用包数据脚本
 * 运行方式: ts-node scripts/init-credit-packages.ts
 */
async function initCreditPackages() {
  try {
    // 初始化数据库连接
    await AppDataSource.initialize();
    console.log('数据库连接已初始化');

    const creditPackageRepository = AppDataSource.getRepository(CreditPackage);

    // 检查是否已有数据
    const existingPackages = await creditPackageRepository.find();
    if (existingPackages.length > 0) {
      console.log(`数据库中已有 ${existingPackages.length} 个信用包，跳过初始化`);
      await AppDataSource.destroy();
      return;
    }

    // 预定义的信用包数据
    const packages = [
      {
        id: 'basic',
        name: 'Basic',
        price: 9.99,
        credits: 10,
        validDays: 30,
        popular: false,
        features: [
          '10 room redesigns',
          'Standard resolution images',
          '5 design styles',
          'Valid for 30 days'
        ]
      },
      {
        id: 'pro',
        name: 'Pro',
        price: 19.99,
        credits: 25,
        validDays: 60,
        popular: true,
        features: [
          '25 room redesigns',
          'High resolution images',
          'All design styles',
          'Download options',
          'Valid for 60 days'
        ]
      },
      {
        id: 'premium',
        name: 'Premium',
        price: 49.99,
        credits: 75,
        validDays: 90,
        popular: false,
        features: [
          '75 room redesigns',
          'Ultra-high resolution images',
          'All design styles',
          'Priority processing',
          'Download options',
          'Valid for 90 days'
        ]
      }
    ];

    // 插入数据
    for (const pkg of packages) {
      const creditPackage = creditPackageRepository.create(pkg);
      await creditPackageRepository.save(creditPackage);
      console.log(`已创建信用包: ${pkg.name}`);
    }

    console.log('信用包初始化完成');
    await AppDataSource.destroy();
  } catch (error) {
    console.error('初始化信用包时出错:', error);
    if (AppDataSource.isInitialized) {
      await AppDataSource.destroy();
    }
    process.exit(1);
  }
}

initCreditPackages();